package com.rmb.util;

import com.rmb.common.exception.ExceptionCast;
import com.rmb.common.model.response.CommonCode;

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import java.io.*;
import java.util.Objects;

/**
 * @author wan
 * @Title: CompileUtil
 * @Package util
 * @Description: wan
 * @date 2021/1/1416:23
 */
public class CompileUtil {

    /**requireNonNull  判断这个对象是否为空,不为空则返回值*/
    static String s = Objects.requireNonNull(Thread.currentThread().getContextClassLoader().getResource("com/rmb/entity/files")).toString();

    static String replace = s.replace("file:/", "");

    public static String addEngIneCode(String className) throws Exception {
        String code= "import java.util.Map;\n" +
                "public class "+className+"{\n" +
                "\tpublic void execute(Map<String, Object> params){\n" +
                "\t\tSystem.out.println(\"hello word linxi\");\n" +
                "\t}\n" +
                "}";
        File file = new File(replace + "/" + className + ".java");
        //没有文件则创建
        if(!file.exists()){
            //mkdir()是创建子目录。
            //mkdirs()是创建多级目录。
            boolean mkdirs = file.getParentFile().mkdirs();
            //根据抽象路径创建一个新的空文件，当抽象路径制定的文件存在时，创建失败
            boolean newFile = file.createNewFile();
            System.out.println("mkdir:"+mkdirs+",newFile:"+newFile);
        }
        //是否编译成功
        Boolean run = compileRun(code, file);
        if(!run){
            ExceptionCast.cast(CommonCode.FAIL);
        }
        return code;
    }

    public static String updateEngineCode(String className,String compileJava) throws Exception {
        File file = new File(replace + "/" + className + ".java");
        //存在文件则删除
        if(file.exists()){
            boolean delete = file.delete();
            System.out.println("存在则删除:"+delete);
        }
        Boolean run = compileRun(compileJava, file);
        if(!run){
            ExceptionCast.cast(CommonCode.FAIL);
        }
        return compileJava;
    }

    public static Boolean compileRun(String code,File file) throws Exception {
        //将Java代码以字符串的形式，先写入文件，然后再通过编译器读取出来，达到动态的效果。
        BufferedWriter bw = new BufferedWriter(new FileWriter(file));
        //写入文件
        bw.write(code);
        bw.flush();
        bw.close();
        //编译
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        //InputStream in, OutputStream out, OutputStream err, String... arguments
        int run2 = compiler.run(null, null, null, file.toString());
        return run2 == 0;
    }

    public static void main(String[] args) throws Exception {
        System.out.println("HelloWordlinxi");
        System.out.println("3组最牛逼");
        String bb= "aaaa";
        String s = addEngIneCode(bb);
        System.out.println(s);
    }
}
